﻿using System.Collections.Generic;
using System.Linq;
using MiniWeb.Core.Dtos;
using MiniWeb.Core.Entities;
using MiniWeb.Core.Entities;
using WFramework.MvcPager;
using WFramework.ORM;

namespace MiniWeb.Dao
{
    public class NewsDao : BaseDao<News>
    {
        public PagedList<NewsDto> GetPagedList(int? rid, int? tid, bool? isHot, string newstitle, int pageIndex, int pageSize)
        {
            var sql = Sql.Builder.Select("ID,NewType,TypeName,Title,CreateDate,ParentType,IsHot").From("News with(nolock)").Where("1=1");
            if (tid != null)
            {
                sql.Where("NewType = @0", tid);
            }
            if(isHot!=null)
            {
                sql.Where("IsHot = @0", isHot);
            }
            if (rid != null)
            {
                sql.Where("ParentType = @0", rid);
            }
            if (!string.IsNullOrEmpty(newstitle))
            {
                sql.Where("Title LIKE @0", string.Format("%{0}%", newstitle));
            }
            sql.OrderBy("CreateDate DESC");
            return PagedList<NewsDto>(pageIndex, pageSize, sql);
        }

        public News GetById(int id)
        {
            var sql = Sql.Builder.Where("id = @0", id);
            return FirstOrDefault(sql);
        }

        public void Delete(int id)
        {
            var sql = Sql.Builder.Where("ID = @0", id);
            Delete(sql);
        }


        public bool Exists(int id)
        {
            var sql = Sql.Builder.Where("ID = @0", id);
            if (FirstOrDefault(sql) != null)
            {
                return true;
            }
            return false;
        }

        public List<NewsDto> GetGongLvList(int top)
        {
            var sql =
                Sql.Builder.Append(
                    "SELECT  TOP " + top.ToString() + "  ID,TypeName,NewType,Title,CreateDate,ParentType FROM News AS T WHERE ID IN(SELECT TOP 5 ID FROM News WHERE NewType=T.NewType AND ParentType =1  ORDER BY CreateDate DESC)  ");
            return Query<NewsDto>(sql).ToList();
        }

        public List<News> GetAll(int? top, string strwhere)
        {
            string sqltop = "";
            if (top != null)
            {
                sqltop = "TOP " + top.ToString() + " ID,TypeName,NewType,Title,CreateDate,ParentType ";
            }
            else
            {
                sqltop = " ID,NewType,Title,CreateDate,ParentType ";
            }
            var sql = Sql.Builder.Select(sqltop).From(" News WITH(NOLOCK)");
            if (!string.IsNullOrEmpty(strwhere))
            {
                sql.Where(strwhere);
            }
            sql.OrderBy("CreateDate Desc");
            return Query<News>(sql).ToList();
        }



    }
}